﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FightManager : MonoBehaviour {

    #region 单例模式
    private static FightManager _instance;

    public static FightManager Instance {
        get {
            if (_instance == null) {
                _instance = GameObject.Find("FightManager").GetComponent<FightManager>();
            }
            return _instance;
        }
    }
    #endregion

    /// <summary>
    /// 回合
    /// </summary>
    private int Round;
    /// <summary>
    /// 最大回合
    /// </summary>
    private int MaxRound;
    private List<Personage> FightTeam;
    private int CurrentActionPersonageIndex;
    private SimpleShowHideComponent AutoText;
    private Text GameOverText;
    private Text RoundText;
    private LoadingPanel LoadingPanel;
    //private DamageText TheDamageText;

    private GlobalData GlobalData;
    private GameManager GameManager;
    private FightPersonage[] FightPersonages;
    /// <summary>
    /// 是否开启了自动攻击
    /// </summary>
    private bool IsAutoAttack;
    /// <summary>
    /// 是否在等待
    /// </summary>
    private bool IsRunning;


    private void Awake() {
        this.GlobalData = GlobalData.Instance;
        this.GameManager = GameManager.Instance;
        int count = this.GlobalData.EnemyTeam.Count;
        int range = count > 3 ? 3 : count;
        this.GlobalData.EnemyFightTeam = this.GlobalData.EnemyTeam.GetRange(0, range);

        count = this.GlobalData.OurTeam.Count;
        range = count > 3 ? 3 : count;
        this.GlobalData.OurFightTeam = this.GlobalData.OurTeam.GetRange(0, range);

        foreach (Personage personage in this.GlobalData.EnemyFightTeam) {
            personage.EnemyFightTeam = this.GlobalData.OurFightTeam;
        }
        foreach (Personage personage in this.GlobalData.OurFightTeam) {
            personage.EnemyFightTeam = this.GlobalData.EnemyFightTeam;
        }
    }

    // Use this for initialization
    void Start() {
        this.GameOverText = GameObject.Find("GameOverInfo").GetComponent<Text>();
        this.GameOverText.gameObject.SetActive(false);
        this.RoundText = GameObject.Find("RoundText").GetComponent<Text>();
        this.AutoText = GameObject.Find("AutoText").GetComponent<SimpleShowHideComponent>();
        this.LoadingPanel = GameObject.Find("LoadingPanel").GetComponent<LoadingPanel>();
        //TheDamageText = GameObject.Find("DamageText").GetComponent<DamageText>();
        this.FightPersonages = GameObject.Find("Person").GetComponentsInChildren<FightPersonage>();
        foreach (FightPersonage fightPersonage in this.FightPersonages) {
            fightPersonage.Init();
        }

        //StartCoroutine(this.WaitStartRound());
        this.StartRound();
    }

    // Update is called once per frame
    void Update() {

    }

    IEnumerator WaitStartRound() {
        yield return new WaitForSeconds(1);
        this.StartRound();
    }

    /// <summary>
    /// 根据人物id查询人物模型。如果不存在，则返回null
    /// </summary>
    /// <param name="personageId">人物id</param>
    /// <returns>人物模型</returns>
    public FightPersonage GetFightPersonage(string personageId) {
        foreach (FightPersonage fightPersonage in FightPersonages) {
            if (personageId.Equals(fightPersonage.PersonageId)) {
                return fightPersonage;
            }
        }
        return null;
    }

    /// <summary>
    /// 开始一个新的回合
    /// </summary>
    public void StartRound() {
        this.Round++;
        RoundText.text = this.Round + "回合";
        /**
         * 回复体力
         **/
        foreach (Personage personage in this.GlobalData.OurFightTeam) {
            RecoverVit(personage);
        }
        foreach (Personage personage in this.GlobalData.EnemyFightTeam) {
            RecoverVit(personage);
        }
        /**
         * 中毒效果
         **/
        // TODO
        this.IsRunning = false;
    }

    /// <summary>
    /// 每回合恢复体力
    /// </summary>
    /// <param name="personage">每回合恢复体力</param>
    /// <returns></returns>
    private int RecoverVit(Personage personage) {
        int hpStatusCode = personage.GetHpStatusCode();
        int MaxVit = personage.MaxVit;
        int recoverVit = 10;
        if (hpStatusCode == 3 || hpStatusCode == 4) { // 死亡或濒死状态
            recoverVit = 0;
        } else if (hpStatusCode == 2) { // 重伤状态
            recoverVit = GameHelper.Multi(recoverVit, Constant.HP_SEVERE_WOUND_RATIO);
        } else if (hpStatusCode == 1) { // 轻伤状态
            recoverVit = GameHelper.Multi(recoverVit, Constant.HP_SLIGHT_WOUND_RATIO);
        }
        int currentVit = personage.Vit + recoverVit;
        if (currentVit > MaxVit) {
            recoverVit = MaxVit - currentVit + recoverVit;
            currentVit = MaxVit;
        }
        personage.Vit = currentVit;

        FightPersonage fightPersonage = this.GetFightPersonage(personage.PersonageId);
        fightPersonage.NumberTips.ShowVit(recoverVit, fightPersonage.gameObject);
        return recoverVit;
    }

    /// <summary>
    /// 其他人选择武学和攻击目标
    /// </summary>
    public void ChooseWuxueAndAttackTarget() {
        for (int i = 0; i < this.GlobalData.OurFightTeam.Count; i++) {
            Personage personage = this.GlobalData.OurFightTeam[i];
            //personage.EnemyFightTeam = this.GlobalData.EnemyFightTeam;
            if (i == 0 || personage.GetHpStatusCode() >= 3) { // 是主角或者濒死死亡的人物
                continue;
            }
            personage.ChooseFightWuxue(); // 选择武学
            PersonageWuxue attWuxue = personage.AttWuxue;
            if (attWuxue != null) { // 选择了攻击武学
                WuxueGrade wuxueGrade = attWuxue.GetWuxueGrade();
                if (wuxueGrade.AttRange == Constant.AttackRange.Single) { // 如果是攻击单人
                    personage.ChooseAttackTarget(); // 选择目标
                }
            }
        }
        foreach (Personage personage in this.GlobalData.EnemyFightTeam) {
            //personage.EnemyFightTeam = this.GlobalData.OurFightTeam;
            if (personage.Hp == 0) { // 生命值为0
                continue;
            }
            personage.ChooseFightWuxue(); // 选择武学
            PersonageWuxue attWuxue = personage.AttWuxue;
            if (attWuxue != null) { // 选择了攻击武学
                WuxueGrade wuxueGrade = attWuxue.GetWuxueGrade();
                if (wuxueGrade.AttRange == Constant.AttackRange.Single) { // 如果是攻击单人
                    personage.ChooseAttackTarget(); // 选择目标
                }
            }
        }
    }

    /// <summary>
    /// 战斗行动
    /// </summary>
    public void FightAction() {
        this.ChooseWuxueAndAttackTarget();

        this.FightTeam = new List<Personage>();
        foreach (Personage personage in this.GlobalData.OurFightTeam) {
            if (personage.Hp == 0) {
                continue;
            }
            //int speed = personage.GetAttackSpeed();
            //personage.ActionSpeed = speed;
            //if (speed > 0) { // 带有攻击目的的放入列表
            // personage.EnemyFightTeam = this.EnemyFightTeam;
            this.FightTeam.Add(personage);
            //}
        }
        foreach (Personage personage in this.GlobalData.EnemyFightTeam) {
            if (personage.Hp == 0) {
                continue;
            }
            //int speed = personage.GetAttackSpeed();
            //personage.ActionSpeed = speed;
            //if (speed > 0) { // 带有攻击目的的放入列表
            // personage.EnemyFightTeam = this.OurFightTeam;
            this.FightTeam.Add(personage);
            //}
        }
        this.FightTeam.Sort((Personage a, Personage b) => { return -a.ActionSpeed.CompareTo(b.ActionSpeed); }); // 速度降序排序
        // 开始当前回合
        CurrentActionPersonageIndex = 0;
        PersonageStartAction();
    }

    public void PersonageStartAction() {
        Personage player = this.GlobalData.GetPlayerPersonage();
        if (player.Hp == 0) { // 主角阵亡
            Debug.Log("主角阵亡");
            this.GameOverText.text = "你挂了";
            this.GameOverText.gameObject.SetActive(true);
            this.FightFinish();
            this.GameManager.Invoke("BackToMenu", 2);
            return;
        }
        bool allEnemyDead = true;
        foreach (Personage p in this.GlobalData.EnemyFightTeam) {
            if (p.Hp > 0) {
                allEnemyDead = false;
                break;
            }
        }
        if (allEnemyDead) {
            this.GameOverText.text = "战斗胜利";
            this.GameOverText.gameObject.SetActive(true);
            this.FightFinish();
            this.GameManager.KillTrigger();
            this.LoadingPanel.LoadScene(this.GlobalData.SceneName);
            return;
        }
        if (this.CurrentActionPersonageIndex >= this.FightTeam.Count) { // 本回合所有人都进行了行动
            StartRound();
            if (this.IsAutoAttack) { // 如果开启了自动攻击
                this.AutoAttack();
            }
            return;
        }
        Personage personage = this.FightTeam[this.CurrentActionPersonageIndex];
        if (personage.Hp != 0) { // 行动执行者未死
            Constant.FightActionCategory fightActionCategory = personage.FightActionCategory;
            FightPersonage fightPersonage = GetFightPersonage(personage.PersonageId);
            if (fightActionCategory == Constant.FightActionCategory.Attack) { // 攻击行为
                Personage attackTargetPersonage = personage.AttackTargetPersonage;
                if (attackTargetPersonage.Hp == 0) { // 攻击目标已死
                    personage.ChooseAttackTarget();
                    attackTargetPersonage = personage.AttackTargetPersonage;
                }
                FightPersonage fightTargetPersonage = GetFightPersonage(attackTargetPersonage.PersonageId);
                fightPersonage.Attack(fightTargetPersonage);
            } else if (fightActionCategory == Constant.FightActionCategory.ResistPoison) { // 御毒
                fightPersonage.ResistPoison();
            } else if (fightActionCategory == Constant.FightActionCategory.UseArticle) { // 使用物品
                fightPersonage.UseArticle();
            } else if (fightActionCategory == Constant.FightActionCategory.Rest) { // 休息
                fightPersonage.Rest();
            } else if (fightActionCategory == Constant.FightActionCategory.Escape) { // 逃跑
                fightPersonage.Escape();
            }
            this.CurrentActionPersonageIndex++;
        } else {
            this.CurrentActionPersonageIndex++;
            this.PersonageStartAction();
        }
    }

    public void OneRound() {
        if (this.Round != 0) {
            FightAction();
        }
        StartRound();
        ChooseWuxueAndAttackTarget();
    }

    /// <summary>
    /// 逃跑成功
    /// </summary>
    public void EscapeSuccess() {
        this.FightFinish();
        this.GlobalData.IsEscaping = true; // 正在逃跑
        this.LoadingPanel.LoadScene(this.GlobalData.SceneName);
    }

    /// <summary>
    /// 点击药品
    /// </summary>
    /// <param name="articleInfo"></param>
    public void ClickDrug(ArticleInfo articleInfo) {
        this.IsRunning = true;
        Personage personage = this.GlobalData.GetPlayerPersonage();
        personage.FightActionCategory = Constant.FightActionCategory.UseArticle;
        personage.ActionSpeed = GameHelper.Multi(personage.CurrentSpeed, Constant.FightSelfSpeedRatio) + Constant.FightUseArticleSpeed;
        personage.FightArticleInfo = articleInfo;
        this.FightAction();
    }

    /// <summary>
    /// 点击逃跑按钮
    /// </summary>
    public void ClickEscape() {
        if (!this.IsRunning) {
            this.IsRunning = true;
            Personage personage = this.GlobalData.GetPlayerPersonage();
            personage.FightActionCategory = Constant.FightActionCategory.Escape;
            personage.ActionSpeed = GameHelper.Multi(personage.CurrentSpeed, Constant.FightSelfSpeedRatio) + Constant.FightEscapeSpeed;
            this.FightAction();
        }
    }

    /// <summary>
    /// 点击御毒按钮
    /// </summary>
    public void ClickResistPoison() {
        if (!this.IsRunning) {
            this.IsRunning = true;
            Personage personage = this.GlobalData.GetPlayerPersonage();
            personage.FightActionCategory = Constant.FightActionCategory.ResistPoison;
            personage.ActionSpeed = GameHelper.Multi(personage.CurrentSpeed, Constant.FightSelfSpeedRatio) + Constant.FightResistPoisonSpeed;
            this.FightAction();
        }
    }

    /// <summary>
    /// 点击休息按钮
    /// </summary>
    public void ClickRest() {
        if (!this.IsRunning) {
            this.IsRunning = true;
            Personage personage = this.GlobalData.GetPlayerPersonage();
            personage.FightActionCategory = Constant.FightActionCategory.Rest;
            personage.ActionSpeed = 0;
            this.FightAction();
        }
    }

    /// <summary>
    /// 点击攻击按钮
    /// </summary>
    public void ClickAttack() {
        if (!this.IsRunning) {
            this.IsRunning = true;
        }
    }

    /// <summary>
    /// 点击选择攻击目标
    /// </summary>
    public void ClickChooseAttackTarget() {
        if (!this.IsRunning) {
            this.IsRunning = true;
            Personage personage = this.GlobalData.GetPlayerPersonage();
            personage.FightActionCategory = Constant.FightActionCategory.Attack;
            personage.AttWuxue = this.GlobalData.FightWuxueGroups[this.GlobalData.FightWuxueGroupIndex].AttackWuxue; // 攻击武学
            personage.DefWuxue = this.GlobalData.FightWuxueGroups[this.GlobalData.FightWuxueGroupIndex].DefenseWuxue; // 防御武学
            personage.ActionSpeed = personage.GetAttackSpeed();
            personage.ChooseAttackTarget(); // 攻击目标
            this.FightAction();
        }
    }

    /// <summary>
    /// 点击自动攻击按钮
    /// </summary>
    public void ClickAutoAttack() {
        this.IsAutoAttack = !this.IsAutoAttack;
        if (this.IsAutoAttack) { // 如果开启了自动攻击
            this.AutoText.Show();
        } else {
            this.AutoText.Hide();
        }
        if (!this.IsRunning) {
            this.AutoAttack();
        }
    }

    /// <summary>
    /// 自动攻击
    /// </summary>
    private void AutoAttack() {
        this.IsRunning = true;
        Personage personage = this.GlobalData.GetPlayerPersonage();
        personage.FightActionCategory = Constant.FightActionCategory.Attack;
        personage.AttWuxue = this.GlobalData.FightWuxueGroups[this.GlobalData.FightWuxueGroupIndex].AttackWuxue; // 攻击武学
        personage.DefWuxue = this.GlobalData.FightWuxueGroups[this.GlobalData.FightWuxueGroupIndex].DefenseWuxue; // 防御武学
        personage.ActionSpeed = personage.GetAttackSpeed();
        personage.ChooseAttackTarget();
        this.FightAction();
    }

    /// <summary>
    /// 战斗结束，清空一些数据
    /// </summary>
    public void FightFinish() {
        List<Personage> all = new List<Personage>();
        all.AddRange(this.GlobalData.OurFightTeam);
        all.AddRange(this.GlobalData.EnemyFightTeam);
        foreach (Personage personage in all) {
            personage.AttackTargetPersonage = null;
            personage.EnemyFightTeam = null;
        }
    }
}
